package com.apobates.jforum2.troll.accounts.biz.impl;

import com.apobates.jforum2.troll.accounts.biz.MemberOnlineService;
import com.apobates.jforum2.troll.accounts.biz.dao.MemberOnlineDao;
import com.apobates.jforum2.troll.accounts.entity.MemberOnline;
import com.apobates.jforum2.troll.utils.core.DateTimeUtils;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import java.util.stream.Stream;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
 *
 * @author xiaofanku
 * @since 20200515
 */
@Service
public class MemberOnlineServiceImpl implements MemberOnlineService{
    @Autowired
    private MemberOnlineDao memberOnlineDao;
    private final static Logger logger = LoggerFactory.getLogger(MemberOnlineServiceImpl.class);
    
    @Override
    public Stream<MemberOnline> getForNow() {
        LocalDateTime finish = LocalDateTime.now();
        LocalDateTime start = DateTimeUtils.beforeMinuteForDate(finish, 30);
        return get(start, finish);
    }
    
    @Override
    public Stream<MemberOnline> get(List<Long> memberIdList) {
        if (null == memberIdList || memberIdList.isEmpty()) {
            return Stream.empty();
        }
        return memberOnlineDao.findAll(memberIdList);
    }
    
    @Override
    public Stream<MemberOnline> get() {
        return memberOnlineDao.findAll();
    }
    
    @Override
    public Stream<MemberOnline> get(LocalDateTime start, LocalDateTime finish) {
        return memberOnlineDao.findAll(start, finish);
    }
    
    @Override
    public Optional<MemberOnline> get(long memberId) {
        if(memberId>0){
            return memberOnlineDao.findOneByMember(memberId);
        }
        return Optional.empty();
    }
    
    @Override
    public long create(MemberOnline memberOnline) {
        MemberOnline obj = memberOnlineDao.findOne(memberOnline.getId()).orElse(null);
        if (null == obj) {
            try {
                memberOnlineDao.save(memberOnline);
                return memberOnline.getMid();
            } catch (Exception e) {
                if(logger.isDebugEnabled()){
                    logger.debug("创建或更新会员在线记录失败", e);
                }
            }
        } else {
            //可能重新登录了
            obj.setMid(memberOnline.getMid());
            obj.setMemberNickname(memberOnline.getMemberNickname());
            obj.setMemberNames(memberOnline.getMemberNames());
            //
            obj.setAction(memberOnline.getAction());
            obj.setActiveDateTime(memberOnline.getActiveDateTime());
            memberOnlineDao.edit(obj);
        }
        return 0L;
    }
    
    @Override
    public long count(LocalDateTime start, LocalDateTime finish) {
        return memberOnlineDao.countByDateTime(start, finish);
    }
}